#!/bin/sh

set -e

### BEGIN INIT INFO
# Provides:	nipapd
# Required-Start:	$remote_fs $network postgresql
# Required-Stop:	$remote_fs $network postgresql
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	NIPAP XML-RPC server
### END INIT INFO

DAEMON=/usr/bin/nipapd
CONFIGFILE=/etc/nipap/nipap.conf
NAME=NIPAPd
PIDFILE=/var/run/nipap/nipapd.pid
PIDDIR=`dirname $PIDFILE`

. /lib/lsb/init-functions

RUN=no
# include defaults if available
if [ -f /etc/default/nipapd ]; then
	. /etc/default/nipapd
fi

if [ "$RUN" != "yes" ]; then
	log_action_msg "$NAME disabled; edit /etc/default/nipapd"
	exit 0
fi

ARGS=""
if [ "$AUTO_INSTALL" = "yes" ]; then
	ARGS="$ARGS --auto-install-db "
fi

if [ "$AUTO_UPGRADE" = "yes" ]; then
	ARGS="$ARGS --auto-upgrade-db "
fi

running() {
	# create dir for PID file if it doesn't exist
	if [ ! -d "$PIDDIR" ]; then
		mkdir "$PIDDIR"
		chown nipap:nipap $PIDDIR
	fi

	if [ $(flock -xn $PIDFILE -c 'echo 1' 2> /dev/null) ]; then
		echo -n
		rm -f $PIDFILE > /dev/null 2>&1
	else
		cat $PIDFILE || echo -n
	fi
}


case "$1" in
	start)
		log_daemon_msg "Starting NIPAPd XML-RPC server" "nipapd"
		RUNNING=$(running)
		if [ -n "$RUNNING" ]; then
			log_progress_msg "already running"
			log_end_msg 0
		else
			if start-stop-daemon --start --exec $DAEMON -- -c $CONFIGFILE $ARGS; then
				log_end_msg 0
			else
				log_end_msg 1
			fi
		fi
		;;
	stop)
		log_daemon_msg "Stopping NIPAPd XML-RPC server" "nipapd"
		RUNNING=$(running)
		if [ -n "$RUNNING" ]; then
			if start-stop-daemon --stop --pidfile $PIDFILE --retry 30; then
				log_end_msg 0
			else
				log_end_msg 1
			fi
		else
			log_end_msg 0
		fi
		;;
	reload)
		log_daemon_msg "Reloading NIPAPd XML-RPC server's configuration" "nipapd"
		RUNNING=$(running)
		if [ -n "$RUNNING" ]; then
			if start-stop-daemon --stop --signal HUP --pidfile $PIDFILE; then
				log_end_msg 0
			else
				log_end_msg 1
			fi
		else
			log_failure_msg "NIPAPd XML-RPC server not running"
		fi
		;;
	force-reload)
		$0 reload
		;;
	restart)
		log_daemon_msg "Restarting NIPAPd XML-RPC server" "nipapd"
		RUNNING=$(running)
		if [ -n "$RUNNING" ]; then
			if start-stop-daemon --stop --pidfile $PIDFILE; then
				if start-stop-daemon --start --exec $DAEMON -- -c $CONFIGFILE $ARGS; then
					log_end_msg 0
				else
					log_end_msg 1
				fi
			else
				log_end_msg 1
			fi
		else
			if start-stop-daemon --start --exec $DAEMON -- -c $CONFIGFILE $ARGS; then
				log_end_msg 0
			else
				log_end_msg 1
			fi
		fi
		;;
	status)
		RUNNING=$(running)
		if [ -n "$RUNNING" ]; then
			log_success_msg "NIPAPd XML-RPC server running with PID $RUNNING"
			exit 0
		else
			log_failure_msg "NIPAPd XML-RPC not running"
			exit 3
		fi
		;;
	*)
		log_action_msg "Usage: /etc/init.d/nipapd {start|stop|restart|reload|force-reload|status}"
esac

exit 0
